<template>
  <div class="update-name">
    <!-- 顶部标题 -->
    <van-nav-bar
      title="设置昵称"
      left-text="返回"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onComfirm"
    />

    <!-- left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight" -->
    <!-- 顶部标题 -->

    <!-- 输入框 -->
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="1"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入留言"
        show-word-limit
        border
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user.js";
export default {
  name: "updateName",
  data() {
    return {
      localName: this.value,
    };
  },
  props: {
    value: {
      type: String,
      required: true,
    },
  },
  methods: {
    async onComfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true, //禁用背景点击
        duration: 0, //持续展示 知道遇到后面的this.$toast方法 就会自动关闭前面的$toast;
      });

      try {
        // 如果昵称为空 则提示
        let localName = this.localName;

        if (!localName.length) {
          this.$toast("昵称不能为空!");
          return;
        }
        await updateUserProfile({
          name: localName,
        });
        // 更新视图
        this.$emit("input", localName);
        // 关闭弹层
        this.$emit("close");
        // 提示成功;
        this.$toast.success("昵称更新成功!");
      } catch (err) {
        this.$toast("更新名字失败!");
      }
    },
  },
};
</script>

<style scoped lang="less">
.field-wrap {
  padding: 10px;
}
</style>
